package com.logistics.system.consumer.listener;




import com.logistics.common.core.constant.Constants;
import com.logistics.common.core.web.domain.AjaxResult;
import com.logistics.system.domain.*;
import com.logistics.system.service.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class SpringRabbitListener {

    @Autowired
    private IPayTradeService payTradeService;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private ITransportPlansService transportPlansService;
    @Autowired
    private IWaybillsService waybillsService;
    @Autowired
    private IContractsService contractsService;

    //
    @RabbitListener(queues = "basic.queue1")
    public void listenerMessage(Long msg) {
        PayTrade payTrade = payTradeService.selectPayTradeByTradeId(msg);

        Long payerId=payTrade.getPayer();//付款人
        Long payeeId=payTrade.getPayee();//收款人

        BigDecimal price = payTrade.getPrice();//应付金额


        BankCard payerBankCard = bankCardService.selectBankCardByUserId(payerId);//付款人余额
//        System.out.println(payerBankCard);
        BigDecimal payerBalance =payerBankCard.getBalance();


        BankCard payeeBankCard = bankCardService.selectBankCardByUserId(payeeId);//收款人余额
//        System.out.println(payeeBankCard);
        BigDecimal payeeBalance =payeeBankCard.getBalance();

        payerBalance= payerBalance.subtract(price);
//        System.out.println(payerBankCard);
        payeeBalance= payeeBalance.add(price);
//        System.out.println(payeeBankCard);


        payerBankCard.setBalance(payerBalance);
//        System.out.println(payerBankCard);
        payeeBankCard.setBalance(payeeBalance);
//        System.out.println(payeeBankCard);

        //支付
        bankCardService.updateBankCard(payerBankCard);
        bankCardService.updateBankCard(payeeBankCard);



        payTrade.setTradeStatus(Constants.TRADE_STATUS_2);
        payTradeService.updatePayTrade(payTrade);

        Waybills waybills = waybillsService.selectWaybillsByWaybillId((payTrade.getWaybillId()));
        waybills.setWaybillStatus(Constants.WAYBILL_STATUS_3);
        waybillsService.updateWaybills(waybills);




        Long planId=waybillsService.selectTransportPlanIdByWaybillId((payTrade.getWaybillId()));
        System.out.println(planId);
        TransportPlans transportPlans = transportPlansService.selectTransportPlansByPlanId(planId);
        transportPlans.setPlanStatus(Constants.PLAN_STATUS_2);
        transportPlansService.updateTransportPlans(transportPlans);

        System.out.println("支付成功");
    }

}
